package com.everflourish.yeah100.adapter;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.RippleDrawable;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.markingsystem.ProofreadCorrectActivity;
import com.everflourish.yeah100.entity.marking.ErrorExamitation;
import com.everflourish.yeah100.entity.marking.OssPicture;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 校对数据的适配器
 * 作者：Created by whf on 2016/11/28.
 */
public class ProofreadingAdapter extends RecyclerView.Adapter<ProofreadingAdapter.ProofreadingViewholder> implements View.OnClickListener {

    private List<ErrorExamitation> mList;
    private final int EXPRECTION_TYPE1 = 1;
    private final int THROWS_TYPE2 = 2;
    private Context context;
    private View exprectionHeadView = null, throwHeadView = null;//异常和可疑试卷的view
    private LayoutInflater inflater;
    private int throwsLength;
    private int exprectLength;
    private List<ErrorExamitation> exprectList, throwsList;
    private String lastModifiedTime;

    public ProofreadingAdapter(Context context, List<ErrorExamitation> list, String lastModifiedTime) {
        mList = list;
        this.lastModifiedTime = lastModifiedTime;
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getItemCount() {
        if (mList != null)
            return mList.size() + (exprectLength > 0 ? 1 : 0) + (throwsLength > 0 ? 1 : 0);
        return 0;
    }

    @Override
    public int getItemViewType(int position) {
        if (exprectLength > 0 && position == 0) {
            return EXPRECTION_TYPE1;
        }
        //考虑三种情况：1、展开第一项，2、关闭第一项、3、两个卡项都关闭了
        if (position == exprectLength + 1
                || (mList.size() == throwsLength && position == 1)
                || (mList.size() == 0 && position == 1)) {
            return THROWS_TYPE2;
        }
        return super.getItemViewType(position);
    }

    @Override
    public ProofreadingViewholder onCreateViewHolder(final ViewGroup parent, int viewType) {
        switch (viewType) {
            case EXPRECTION_TYPE1:
                exprectionHeadView = getHeadView("异常试卷：" + exprectLength, parent);
                exprectionHeadView.setOnClickListener(this);
                return getViewHolder(exprectionHeadView);
            case THROWS_TYPE2:
                throwHeadView = getHeadView("可疑试卷：" + throwsLength, parent);
                throwHeadView.setOnClickListener(this);
                return getViewHolder(throwHeadView);
        }
        View view = inflater.inflate(R.layout.item_proofreading_list, parent, false);
        return getViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ProofreadingViewholder holder, final int position) {
        if (position % 2 == 0) {
            holder.itemView.setBackgroundColor(Color.parseColor("#F0F0F0"));
        } else {
            holder.itemView.setBackgroundColor(Color.WHITE);
        }
        int viewType = getItemViewType(position);
        switch (viewType) {
            case EXPRECTION_TYPE1:
            case THROWS_TYPE2:
                break;
            default:
                int t1 = (exprectLength > 0 ? 1 : 0);
                int t2 = (position > exprectLength || mList.size() == throwsLength ? 1 : 0);
                final int index = position - t1 - t2;
                final ErrorExamitation b = mList.get(index);
                holder.proofeading_nomb.setText("学号：" + b.studentNo);
                holder.proofeading_name.setText("姓名：" + b.studentName);
                holder.proof_detail_error.setText("错误解析：" + b.errorMsg);

                holder.proofread_number_tv.setText((index >= exprectLength ? (index - exprectLength +1) : index+1) +"");
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO: 2016/11/29 跳转
                        ArrayList<String> pictureUrls = new ArrayList<String>();
                        ArrayList<OssPicture> ossPictures = mList.get(index).getAutomateErrorOssUrls();
                        for (OssPicture ossPicture : ossPictures) {
                            pictureUrls.add(ossPicture.getOssUrl());
                        }
                        Intent intent = new Intent(context,
                                ProofreadCorrectActivity.class);
                        intent.putExtra("studentNo", b.studentNo);
                        intent.putExtra("examinationId", b.examinationId);
                        intent.putExtra("pictureUrl", pictureUrls);
                        intent.putExtra("studentName", b.getStudentName());
                        intent.putExtra("lastModifiedTime", lastModifiedTime);
                        context.startActivity(intent);
                    }
                });
                break;
        }
    }

    /**
     * 获取标题viewholder
     *
     * @return
     */
    private ProofreadingViewholder getViewHolder(View v) {
        return new ProofreadingViewholder(v);
    }

    /**
     * 获取标题view
     *
     * @param s
     * @param parent
     * @return
     */
    private View getHeadView(String s, ViewGroup parent) {
        FrameLayout root = new FrameLayout(parent.getContext());
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        root.setLayoutParams(lp);
        TextView tv = new TextView(parent.getContext());
        lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        tv.setLayoutParams(lp);
        tv.setPadding(40, 30, 20, 30);
        tv.setText(s);
        tv.setTypeface(null, Typeface.BOLD);
        tv.setTextSize(16);
        root.addView(tv);
        return root;
    }

    /**
     * 过滤数据
     *
     * @param mlist
     * @return
     */
    private List<ErrorExamitation> filterVisibilityDatas(List<ErrorExamitation> mlist, int type) {
        List<ErrorExamitation> result = new ArrayList<>();
        for (ErrorExamitation b : mlist) {
            if (type == EXPRECTION_TYPE1) {
                if (b.errorType == 1) {
                    result.add(b);
                }
            } else {
                if (b.errorType == 0) {
                    result.add(b);
                }
            }
        }
        return result;
    }

    /**
     * 处理这两个项的收缩和开起逻辑
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        ErrorExamitation b;
        if (v == exprectionHeadView) {
            b = exprectList.get(0);
            if (b.isPexpend) {
                mList.removeAll(exprectList);
            } else {
                mList.addAll(exprectList);
            }
            b.isPexpend = !b.isPexpend;
        }
        if (v == throwHeadView) {
            b = throwsList.get(0);
            if (b.isPexpend) {
                mList.removeAll(throwsList);
            } else {
                mList.addAll(throwsList);
            }
            b.isPexpend = !b.isPexpend;
        }
        sortData();
        notifyDataSetChanged();
    }

    /**
     * 刷新数据
     *
     * @param mList
     */
    public void reflashDate(List<ErrorExamitation> mList) {
        this.mList = mList;
        if (mList != null) {
            sortData();
            exprectList = filterVisibilityDatas(mList, EXPRECTION_TYPE1);
            throwsList = filterVisibilityDatas(mList, THROWS_TYPE2);
            exprectLength = exprectList.size();
            throwsLength = throwsList.size();
        }
        notifyDataSetChanged();
    }

    /**
     * 排序数据
     */
    private void sortData() {
        Collections.sort(mList, new Comparator<ErrorExamitation>() {
            @Override
            public int compare(ErrorExamitation lhs, ErrorExamitation rhs) {
                return -lhs.errorType + rhs.errorType;
            }
        });
    }

    public class ProofreadingViewholder extends RecyclerView.ViewHolder {

        public TextView proofeading_nomb;
        public TextView proofeading_name;
        public TextView proof_detail_error;
        public TextView proofread_number_tv;


        public ProofreadingViewholder(View itemView) {
            super(itemView);
            //  正常部分
            proof_detail_error = (TextView) itemView.findViewById(R.id.proof_detail_error);
            proofeading_name = (TextView) itemView.findViewById(R.id.proofeading_name);
            proofeading_nomb = (TextView) itemView.findViewById(R.id.proofeading_nomb);
            proofread_number_tv = (TextView) itemView.findViewById(R.id.proofread_number_tv);
        }
    }

    /**
     * 获取涟漪波纹
     *
     * @param bgColor     背景
     * @param rippleColor 涟漪波纹色
     * @return
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public Drawable getRippleBg(int bgColor, int rippleColor) {
        GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setColor(bgColor);
        gradientDrawable.setCornerRadius(0);
        RippleDrawable drawable = new RippleDrawable(ColorStateList.valueOf(rippleColor), gradientDrawable, gradientDrawable);
        return drawable;
    }


}